﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace IslandInterloper.Engine
{
    public interface IHeading
    {
        double Degrees { get; }
        double Minutes { get; }
        double Seconds { get; }
        double WholeDegrees { get; }
        double WholeMinutes { get; }
        double WholeSeconds { get; }
        ILocation ToLocation();
    }
    internal class Heading:IHeading
    {
        private double degrees;
        public double Degrees
        {
            get
            {
                return degrees;
            }
            set
            {
                degrees = Utilities.NormalizeDegrees(value);
            }
        }
        public double Minutes
        {
            get
            {
                return (Degrees - WholeDegrees) * 60;
            }
            set
            {
                Degrees = WholeDegrees + value / 60;
            }
        }
        public double Seconds
        {
            get
            {
                return (Minutes - WholeMinutes) * 60;
            }
            set
            {
                Degrees = WholeDegrees + WholeMinutes / 60 + value / 60 / 60;
            }
        }
        public double WholeDegrees
        {
            get
            {
                return Math.Floor(Degrees);
            }
        }
        public double WholeMinutes
        {
            get
            {
                return Math.Floor(Minutes);
            }
        }
        public double WholeSeconds
        {
            get
            {
                return Math.Floor(Seconds);
            }
        }
        internal Heading()
            : this(0)
        {
        }
        internal Heading(double theDegrees)
        {
            Degrees = theDegrees;
        }
        internal Heading(XElement element)
        {
            FromXElement(element);
        }
        public ILocation ToLocation()
        {
            return new Location(Math.Cos(degrees/180.0*Math.PI), Math.Sin(degrees/180.0*Math.PI));
        }
        private void FromXElement(XElement element)
        {
            Degrees = Utilities.XElementToDouble(element);
        }
        public XElement ToXElement(XName xName)
        {
            return new XElement(xName, Degrees);
        }
    }
}
